package cn.codingjc.aurora.framework.oauth.core.spring;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.oauth2.client.userinfo.DefaultOAuth2UserService;
import org.springframework.security.oauth2.client.userinfo.OAuth2UserRequest;
import org.springframework.security.oauth2.core.OAuth2AuthenticationException;
import org.springframework.security.oauth2.core.user.OAuth2User;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.Collections;
import java.util.Map;

/**
 * @ClassName CustomOAuth2UserService
 * @Description Todo
 * @Author jccoding
 * @Date 2024/3/19 10:27
 * @Version 1.0
 **/

@Slf4j
@Service
public class CustomOAuth2UserService extends DefaultOAuth2UserService {

    @Override
    public OAuth2User loadUser(OAuth2UserRequest oAuth2UserRequest) throws OAuth2AuthenticationException {
        OAuth2User oauth2User = super.loadUser(oAuth2UserRequest);
        CustomOAuth2User customOAuth2User = new CustomOAuth2User(oauth2User);
        log.info("Attributes:{}", JSON.toJSONString(customOAuth2User.getAttributes()));
        return customOAuth2User;
    }

    private static class CustomOAuth2User implements OAuth2User {
        private OAuth2User oauth2User;

        public CustomOAuth2User(OAuth2User oauth2User) {
            this.oauth2User = oauth2User;
        }

        @Override
        public String getName() {
            return oauth2User.getAttribute("name");
        }

        @Override
        public Map<String, Object> getAttributes() {
            return oauth2User.getAttributes();
        }

        @Override
        public Collection<? extends GrantedAuthority> getAuthorities() {
            return Collections.singletonList(new SimpleGrantedAuthority("ROLE_USER"));
        }
    }
}
